package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class PassportController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo, Model model){
        UserInfo login = userService.login(userInfo);
        if(login!=null){
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            Map map = new HashMap<>();
            map.put("token",token);
            map.put("name",login.getName());
            map.put("nickName",login.getNickName());
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,login.getId().toString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        }else {
            return Result.fail().message("用户名或密码错误");
        }

    }

    @ApiOperation("退出")
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token"));
        return Result.ok();
    }

    @ApiOperation("根据用户id查询收货地址")
    @GetMapping("/userAddressList")
    public List<UserAddress> userAddressList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userService.userAddressList(userId);
    }

}
